const { config } = require("dotenv");
const fs = require("fs");
const path = require("path");
const prettier = require("prettier");

const createIndexTs = async (projectPath, dirs, context) => {
  await Promise.all(
    dirs.map(async (dir) => {
      const dirPath = path.join(projectPath, dir);
      const mode = fs.readdirSync(dirPath);
      const strObj = mode
        .filter((fileName) => {
          return fileName !== "index.ts";
        })
        .reduce(
          (pre, fileName) => {
            // 判断是否是文件夹
            const statPath = path.join(dirPath, fileName);
            if (fs.statSync(statPath).isDirectory()) {
              createIndexTs(dirPath, [fileName], context);
            }
            const codeName = fileName
              .replace(".ts", "")
              .split("-")
              .map((str, index) =>
                index == 0 ? str : str.charAt(0).toUpperCase() + str.slice(1)
              )
              .join("");
            pre._import += `import ${codeName} from './${fileName.replace(".ts",'')}'\n`;
            pre._export += `${codeName},\n`;

            //
            return pre;
          },
          { _import: "", _export: "" }
        );
      const str = `${strObj._import}\nexport default {\n${strObj._export}\n}`;
      const formattedCode = await prettier.format(str, {
        parser: "typescript",
        ...(context?.prettier || {}),
      });
      fs.writeFileSync(path.join(projectPath, dir, "index.ts"), formattedCode);
    })
  );
};

/**
 * 创建语言文件夹 index 公共导出
 * @param {*} context
 */
const createIndex = async (context) => {
  const { translate, translateEn } = context.catchTmp;

  if (translate && fs.existsSync(translate)) {
    const translateDir = fs.readdirSync(translate);
    await createIndexTs(translate, translateDir, context);
  } else {
    console.warn("translate not found");
  }
  if (translateEn && fs.existsSync(translateEn)) {
    const translateEnDir = fs.readdirSync(translateEn);
    await createIndexTs(translateEn, translateEnDir, context);
  } else {
    console.warn("translateEn not found");
  }
};

module.exports = createIndex;
